package com.yy.tech.data.coder.secret.std;

import com.yy.tech.data.coder.secret.decrypt.Decrypt;
import com.yy.tech.data.coder.secret.encrypt.Encrypt;
import com.yy.tech.data.coder.secret.utils.AES256Encryptor;
import com.yy.tech.data.context.SecretContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;

/**
 * @author yy
 * @date 2022/4/4
 * @description: TODO
 */
@Component
public class Aes256Secret implements Encrypt, Decrypt {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private String secretKey;

    private String parameter;

    @Autowired
    private Environment environment;

    @PostConstruct
    public void initialize(){
        getParameter();
        getSecretKey();
    }
    @Override
    public String decrypt(final String target) {
        if (!StringUtils.isEmpty(target) && target.startsWith(AES256Encryptor.PREFIX)) {
            try {
                return AES256Encryptor.decryptFromBase64(target, secretKey, parameter, false);
            } catch (final Exception e) {
                logger.warn(">> Decrypt[{}] exception {}", target, e.getLocalizedMessage());
            }
        }
        return target;
    }

    @Override
    public String encrypt(final String source) {
        if (!StringUtils.isEmpty(source) && !source.startsWith(AES256Encryptor.PREFIX)){
            try {
                return AES256Encryptor.encryptAsBase64(source, secretKey, parameter, false);
            } catch (final Exception e) {
                logger.warn(">>Encrypt[{}] exception {}", source, e.getLocalizedMessage());
            }
        }
        return source;
    }

    public String getParameter() {
        if (!StringUtils.hasLength(parameter)){
            parameter = environment.getProperty(SecretContent.KEY_DESENSITIZE_SECRET_AES256_PARAM16,SecretContent.DEFAULT_SECRET_AES256_PARAM16);
        }
        return parameter;
    }

    public String getSecretKey() {
        if (!StringUtils.hasLength(secretKey)){
            secretKey = environment.getProperty(SecretContent.KEY_DESENSITIZE_SECRET_AES256_KEY32,SecretContent.DEFAULT_SECRET_AES256_KEY32);
        }
        return secretKey;
    }
}
